from typing import Dict, Tuple
from pathlib import Path
import json
import lzma

class AreaCodeManager:
    """行政区划代码管理器"""
    _instance = None
    _area_dict: Dict[str, str] = {}
    
    def __new__(cls):
        """单例模式实现"""
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._load_data()
        return cls._instance
    
    @classmethod
    def _load_data(cls) -> None:
        """加载区划代码数据"""
        if not cls._area_dict:
            try:
                data_file = Path(__file__).parent / 'area_codes.json.xz'
                with lzma.open(data_file, 'rt', encoding='utf-8') as f:
                    cls._area_dict = json.load(f)
            except Exception as e:
                print(f"警告: 加载区划代码数据失败 - {str(e)}")
                cls._area_dict = {}
    
    def _get_area_code_parts(self, code: str) -> Tuple[str, str, str]:
        """将地区代码拆分为省市县三级代码
        
        Args:
            code: 6位地区代码
            
        Returns:
            Tuple[str, str, str]: (省级代码, 市级代码, 县级代码)
        """
        if len(code) != 6:
            return '', '', ''
            
        province_code = code[:2] + '0000'
        city_code = code[:4] + '00'
        county_code = code
        
        return province_code, city_code, county_code
    
    def get_area(self, code: str) -> str:
        """获取区划代码对应的地区名称
        
        Args:
            code: 行政区划代码
            
        Returns:
            str: 地区名称，如果代码不存在则返回空字符串
        """
        # 如果代码不是6位，直接返回空
        if len(code) != 6:
            return ''
            
        # 获取省市县三级代码
        province_code, city_code, county_code = self._get_area_code_parts(code)
        
        # 获取对应的地区名称
        area_name = ''
        
        # 查找县级名称
        if county_code in self._area_dict:
            area_name = self._area_dict[county_code]
        # 如果县级找不到，查找市级名称
        elif city_code in self._area_dict:
            area_name = self._area_dict[city_code]
        # 如果市级也找不到，查找省级名称
        elif province_code in self._area_dict:
            area_name = self._area_dict[province_code]
            
        return area_name
    
    def get_full_area(self, code: str) -> str:
        """获取完整的行政区划名称（省市县）
        
        Args:
            code: 6位行政区划代码
            
        Returns:
            str: 完整的行政区划名称，例如"湖北省黄冈市"
        """
        if len(code) != 6:
            return ''
            
        # 获取省市县三级代码
        province_code, city_code, county_code = self._get_area_code_parts(code)
        
        # 获取各级地区名称
        province_name = self._area_dict.get(province_code, '')
        city_name = self._area_dict.get(city_code, '')
        county_name = self._area_dict.get(county_code, '')
        
        # 组合完整地区名称
        full_name = ''
        if province_name:
            full_name += province_name
        if city_name and city_name != province_name:  # 避免直辖市重复
            full_name += city_name
        if county_name and county_name not in (province_name, city_name):  # 避免重复
            full_name += county_name
            
        return full_name
    
    @classmethod
    def reload_data(cls) -> None:
        """重新加载区划代码数据"""
        cls._area_dict.clear()
        cls._load_data()